<template>
  <div class="data-auth-contract">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>模块配置及数据权限配置</h3>
        </div>
      </template>

      <el-alert :title="configDetail.desc" type="warning" show-icon :closable="false" />

      <el-form :model="configForm" label-width="120px" label-position="left" class="mt-4">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限名称">
              <el-input v-model="configDetail.title" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input v-model="configDetail.name" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同管理员">
              <el-input
                v-model="configForm.conf_1_str"
                placeholder="请选择权限人员"
                readonly
                @click="selectAdmin(1)"
              >
                <template #append>
                  <el-button @click="clearAdmin(1)">清除</el-button>
                </template>
              </el-input>
              <input type="hidden" v-model="configForm.conf_1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_1" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号自动生成">
              <el-radio-group v-model="configForm.conf_2">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="0">不开启</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_2" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否开启关联客户[销售合同]">
              <el-radio-group v-model="configForm.conf_3">
                <el-radio :label="1">关联</el-radio>
                <el-radio :label="0">不关联</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_3" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否开启关联产品[销售合同]">
              <el-radio-group v-model="configForm.conf_4">
                <el-radio :label="1">关联</el-radio>
                <el-radio :label="0">不关联</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_4" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否开启关联服务[销售合同]">
              <el-radio-group v-model="configForm.conf_5">
                <el-radio :label="1">关联</el-radio>
                <el-radio :label="0">不关联</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_5" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否开启关联供应商[采购合同]">
              <el-radio-group v-model="configForm.conf_6">
                <el-radio :label="1">关联</el-radio>
                <el-radio :label="0">不关联</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_6" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否开启关联采购品[采购合同]">
              <el-radio-group v-model="configForm.conf_7">
                <el-radio :label="1">关联</el-radio>
                <el-radio :label="0">不关联</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_7" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="合同到期前N天提醒"
              prop="conf_10"
              :rules="[{ required: true, message: '请输入合同到期前N天提醒', trigger: 'blur' }]"
            >
              <el-input v-model="configForm.conf_10" placeholder="请输入合同到期前N天提醒" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_10" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm">立即提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 人员选择对话框 -->
    <el-dialog v-model="adminDialogVisible" title="选择人员" width="600px">
      <el-table
        :data="userList"
        highlight-current-row
        @current-change="handleUserSelect"
        v-loading="userLoading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="department" label="部门" />
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adminDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdminSelect">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import {
    getDataauthList as getDataAuthListApi,
    editDataauth as editDataAuthApi,
  } from '@/api/home/dataauth'
  import { useRoute } from 'vue-router'

  // 数据相关
  const route = useRoute()
  const configDetail = ref({
    id: 0,
    title: '',
    name: '',
    desc: '合同模块使用说明：合同模块主要用于管理公司签署的各类合同，包括销售合同和采购合同。合同模块支持合同的创建、审批、归档、中止、作废等全生命周期管理。',
  })
  const configForm = reactive({
    id: 0,
    conf_1: '',
    conf_1_str: '',
    conf_2: 1,
    conf_3: 1,
    conf_4: 1,
    conf_5: 1,
    conf_6: 1,
    conf_7: 1,
    conf_10: '30',
  })

  // 人员选择相关
  const adminDialogVisible = ref(false)
  const userList = ref<any[]>([])
  const userLoading = ref(false)
  const currentAdminField = ref('')

  // 获取合同数据权限配置
  const getContractConfig = async () => {
    try {
      const response: any = await getDataAuthListApi({
        id: route.query.id || 1,
      })

      if (response.data.code === 0) {
        const data = response.data.data
        configDetail.value = data.detail

        // 设置表单数据
        configForm.id = data.detail.id
        configForm.conf_1 = data.detail.conf_1 || ''
        configForm.conf_1_str = data.detail.conf_1_str || ''
        configForm.conf_2 = data.detail.conf_2 !== undefined ? data.detail.conf_2 : 1
        configForm.conf_3 = data.detail.conf_3 !== undefined ? data.detail.conf_3 : 1
        configForm.conf_4 = data.detail.conf_4 !== undefined ? data.detail.conf_4 : 1
        configForm.conf_5 = data.detail.conf_5 !== undefined ? data.detail.conf_5 : 1
        configForm.conf_6 = data.detail.conf_6 !== undefined ? data.detail.conf_6 : 1
        configForm.conf_7 = data.detail.conf_7 !== undefined ? data.detail.conf_7 : 1
        configForm.conf_10 = data.detail.conf_10 || '30'
      } else {
        ElMessage.error(response.data.msg || '获取合同数据权限配置失败')
      }
    } catch (error) {
      ElMessage.error('获取合同数据权限配置失败')
    }
  }

  // 获取用户列表（模拟）
  const getUserList = async () => {
    try {
      userLoading.value = true
      // 这里应该调用实际的用户列表接口
      // const response: any = await getUserListApi()

      // 模拟数据
      userList.value = [
        { id: 1, name: '张三', department: '销售部' },
        { id: 2, name: '李四', department: '财务部' },
        { id: 3, name: '王五', department: '人事部' },
        { id: 4, name: '赵六', department: '技术部' },
      ]
    } catch (error) {
      // 模拟数据
      userList.value = [
        { id: 1, name: '张三', department: '销售部' },
        { id: 2, name: '李四', department: '财务部' },
        { id: 3, name: '王五', department: '人事部' },
        { id: 4, name: '赵六', department: '技术部' },
      ]
    } finally {
      userLoading.value = false
    }
  }

  // 选择管理员
  const selectAdmin = (field: number) => {
    currentAdminField.value = `conf_${field}`
    getUserList()
    adminDialogVisible.value = true
  }

  // 清除管理员
  const clearAdmin = (field: number) => {
    const fieldStr = `conf_${field}_str`
    const fieldId = `conf_${field}`

    if (fieldStr in configForm) {
      ;(configForm as any)[fieldStr] = ''
    }
    if (fieldId in configForm) {
      ;(configForm as any)[fieldId] = ''
    }
  }

  // 处理用户选择
  const selectedUser = ref<any>(null)
  const handleUserSelect = (row: any) => {
    selectedUser.value = row
  }

  // 确认管理员选择
  const confirmAdminSelect = () => {
    if (selectedUser.value) {
      const fieldStr = `${currentAdminField.value}_str`
      const fieldId = currentAdminField.value

      if (fieldStr in configForm) {
        ;(configForm as any)[fieldStr] = selectedUser.value.name
      }
      if (fieldId in configForm) {
        ;(configForm as any)[fieldId] = selectedUser.value.id
      }

      adminDialogVisible.value = false
    } else {
      ElMessage.warning('请选择一个用户')
    }
  }

  // 提交表单
  const submitForm = async () => {
    try {
      const response: any = await editDataAuthApi(configForm)

      if (response.data.code === 0) {
        ElMessage.success('保存成功')
      } else {
        ElMessage.error(response.data.msg || '保存失败')
      }
    } catch (error) {
      ElMessage.error('保存失败')
    }
  }

  // 重置表单
  const resetForm = () => {
    getContractConfig()
  }

  // 初始化
  onMounted(() => {
    getContractConfig()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .mt-4 {
    margin-top: 1rem;
  }
</style>
